/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package core.api;

import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;

/**
 *
 * @author ASUS_2
 */
public class APIUtility {

    public static String generateParam(String param, String value) {
        return param + "=" + URLEncoder.encode(value);
    }

    public static String decrypt(String sourceString) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(sourceString.getBytes());
        byte[] encryptDatas = md.digest();
        String returnData = new BigInteger(1, encryptDatas).toString(16);
        while (returnData.length() < 32) {
            returnData = "0" + returnData;
        }
        return returnData;
    }

    public static String encrypt(String key, String data) throws Exception {
        Cipher cipher = Cipher.getInstance("TripleDES");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(key.getBytes(), 0, key.length());
        String keymd5 = new BigInteger(1, md5.digest()).toString(16).substring(0, 24);
        SecretKeySpec keyspec = new SecretKeySpec(keymd5.getBytes(), "TripleDES");
        cipher.init(Cipher.ENCRYPT_MODE, keyspec);
        byte[] stringBytes = data.getBytes();
        byte[] raw = cipher.doFinal(stringBytes);
        BASE64Encoder encoder = new BASE64Encoder();
        String base64 = encoder.encode(raw);
        return base64;
    }

    public static String getToken(Object... objects) throws NoSuchAlgorithmException {
        String s = "";
        for (Object object : objects) {
            s += object;
        }
        return decrypt(s);
    }
}
